from django.shortcuts import render, redirect
from django.views import View
import jsonpickle
from cart.cartmanager import getCartManger
from django.db.transaction import atomic
from utils.alipay import AliPay
from User.models import *
from goods.models import *
from .models import *
import json, datetime, uuid
from cart.models import *
from django.db.models import F
from django.http import HttpResponse

# Create your views here.
alipay = AliPay(appid='2016102300742039',
                app_notify_url='http://127.0.0.1:8000/order/checkorder',
                app_private_key_path='my_private.txt',
                alipay_public_key_path='alipay_public.txt',
                return_url='http://127.0.0.1:8000/order/checkorder',
                debug=True)


class OrderView(View):
    def get(self, request):
        if not request.session.get('user'):
            return redirect('/user/login?redirect=order&cartitems='+request.GET.get('cartitems'))
        else:
            raw_cartitems = jsonpickle.loads('['+request.GET.get('cartitems')+']')
            request.session['raw_cartitems'] = raw_cartitems
            return redirect('/order/order.html')


class OrderListView(View):
    def get(self, request):
        cartitems = request.session.get('raw_cartitems')
        cartManager = getCartManger(request)
        cart_items = [cartManager.get_cartitems(**item) for item in cartitems]

        address = request.session.get('user').address_set.get(isdefault=True)

        totalprice = 0
        for cartitem in cart_items:
            totalprice += cartitem.total_price()

        return render(request, 'order.html',
                      {'cartitems': cart_items, 'address': address, 'totalprice': totalprice})


class ToOrderView(View):
    @atomic
    def get(self, request):
        cartitems = json.loads(request.GET.get('cartitems'))
        raw_order = {
            'address': Address.objects.get(id=request.GET.get('address')),
            'payway': request.GET.get('payway', 'alipay'),
            'out_trade_num': uuid.uuid4().hex,
            'order_num': datetime.datetime.today().strftime('%Y%m%d%H%M%S'),
            'user': request.session.get('user'),
        }
        order = Order.objects.create(**raw_order)
        total_amount = 0
        for item in cartitems:
            orderitem = OrderItem.objects.create(order=order, **item)
            total_amount += orderitem.total_price()
            CartItem.objects.filter(user=request.session.get('user'), **item).delete()
            Inventory.objects.filter(goods_id=item['goodsid'],
                                     color_id=item['colorid'],
                                     size_id=item['sizeid']).update(
                count=F('count') - int(item['count'])
            )
        if 'raw_cartitems' in request.session:
            del request.session['raw_cartitems']
        params = alipay.direct_pay(subject='九块九电商支付',
                                   total_amount=total_amount,
                                   out_trade_no=order.out_trade_num)
        url = 'https://openapi.alipaydev.com/gateway.do?' + params
        return redirect(url)


class CheckOrderView(View):
    def get(self, request):
        d = request.GET.dict()
        sign = d.pop('sign')
        if alipay.verify(d, sign):
            out_trade_no = d.get('out_trade_no')
            order = Order.objects.get(out_trade_num=out_trade_no)
            if order.status == '待付款':
                order.status = '待发货'
                order.trade_no = d.get('trade_no')
                order.save()
                return HttpResponse('交易成功！')
            else:
                return HttpResponse('交易失败！')